var nameAddress = "n1j1STm7RCfxSPSdvu5ZHotfMUEZP8Ctchb";
var nameHash = "850c07dd129dcbeb40b28ec47b92a4fd6d833c31848ff1d2234d8de5c8556cb0";

function getAddressName (address) {
  nebPay.simulateCall(nameAddress, "0", "getName", JSON.stringify([address]), {
    listener: function(res) {
      if(res.result == '' && res.execute_err == 'contract check failed') {
          toast('合约检测失败，请检查浏览器钱包插件环境！');
          return;
      }
      var info = res.result && JSON.parse(res.result);
      
      if (info) {
        info = JSON.parse(info);
        $('#address').html(info.address);
        $('#name').html(info.name);
        $('#show').show();
      } else {
        $('#add-address').html(window.address);
        $('#add').show();
      }
      $('#loading').hide();
    }
  })
}

$('#add-name').on('input', function () {
  if ($(this).val()) {
    $('#submit').css('display', 'block');
  } else {
    $('#submit').css('display', 'none');
  }
})

$('#submit').on('click', function () {
  if ($('#submit').html() != '注册此短地址') {
    return false;
  }
  $('#submit').html('<img alt="" src="./img/btn-load.png">');
  var value = $('#add-name').val();
  nebPay.simulateCall(nameAddress, "0", "getName", JSON.stringify([value]), {
    listener: function(res) {
      if(res.result == '' && res.execute_err == 'contract check failed') {
          toast('合约检测失败，请检查浏览器钱包插件环境！');
          return;
      }
      var info = res.result && JSON.parse(res.result);
      if (info) {
        toast(value + ':: 已被注册!')
      } else {
        nebPay.call(nameAddress, "0", "setName", JSON.stringify([value]), { 
          listener: function(res) {
            toast(res.txhash ? '注册短地址成功,1分钟后生效,请不要重复注册哦' : '注册短地址失败');
            $('#submit').html('注册此短地址');
          }
        })
      }
    }
  })
})